/*
 * Copyright © 2022
 * @Author: zhangxiang
 * @Date: 2022-08-15 16:16:26
 * @LastEditors: zhangxiang
 * @LastEditTime: 2022-11-03 15:12:07
 * @Description:
 *
 */

/**
 *
 * 时间格式化
 *
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 *
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(), // 年份
    m: date.getMonth() + 1, // 月份
    d: date.getDate(), // 天
    h: date.getHours(), // 小时
    i: date.getMinutes(), // 分钟
    s: date.getSeconds(), // 秒
    a: date.getDay() // 星期
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 *
 * 检查IP地址
 *
 * @param {*} parameter 参数对象
 *
 */
export function parseIpToBinary(ipAddress) {
  const numArray = ipAddress.split('.')
  if (numArray.length !== 4) {
    return
  }
  let returnIpStr = ''
  for (let i = 0; i < 4; i++) {
    const currNum = numArray[i]
    let numberBin = parseInt(currNum)
    numberBin = numberBin.toString(2)
    const iCount = 8 - numberBin.length
    for (let j = 0; j < iCount; j++) {
      numberBin = '0' + numberBin
    }
    returnIpStr += numberBin
  }
  return returnIpStr
}
